package ws_contact

import (
	"encoding/json"
	"errors"
)

type Action uint8

const (
	CheckIn Action = iota
	Report
	Ping
	PieceDelete
)

type Package struct {
	Action Action `json:"action"`
	Data   []byte `json:"data"`
}

func (p *Package) DecData(data any) error {
	return json.Unmarshal(p.Data, &data)
}

func packMsg(p Package) []byte {
	b := make([]byte, 1+len(p.Data))
	b[0] = byte(p.Action)
	copy(b[1:], p.Data)
	return b
}

func UnpackMsg(b []byte) (p *Package, err error) {
	if len(b) < 2 {
		return nil, errors.New("unpack error, length too less")
	}
	p = &Package{Action: Action(b[0])}
	p.Data = b[1:]
	return
}

func PackMsgCheckIn(req CheckInRequest) ([]byte, error) {
	var err error = nil
	pkg := Package{Action: CheckIn}
	pkg.Data, err = json.Marshal(req)
	if err != nil {
		return nil, err
	}
	return packMsg(pkg), nil
}

func PackMsgReport(req ReportRequest) ([]byte, error) {
	var err error = nil
	pkg := Package{Action: Report}
	pkg.Data, err = json.Marshal(req)
	if err != nil {
		return nil, err
	}
	return packMsg(pkg), nil
}
func PackMsgDelRequest(req *PieceDeleteRequest) ([]byte, error) {
	var err error = nil
	pkg := Package{Action: PieceDelete}
	pkg.Data, err = json.Marshal(req)
	if err != nil {
		return nil, err
	}
	data := packMsg(pkg)
	return data, err
}
